package com.zs.games.controller;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zs.games.resultTool.CimResponse;
import com.zs.games.resultTool.ResultCodeEnum;
import com.zs.games.utils.FileDownloadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Api(value = "文件上传管理",tags = "文件上传管理")
@Slf4j
public class ImageUploadController {

    @Value("${upload.path}")
    private String uploadPath;

    @Value("${upload.mapping}")
    private String fileMapping;

    @PostMapping("/file")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "上传文件接口")
    public CimResponse<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return CimResponse.fail(ResultCodeEnum.FAIL);
        }
        try {
            String fileName = UUID.randomUUID() + StringPool.DOT + getFileExtension(file) ;
            File dest = new File(uploadPath + fileName);
            file.transferTo(dest);
            return CimResponse.okData(fileMapping + fileName);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return CimResponse.fail(ResultCodeEnum.FAIL);
        }
    }

    @GetMapping("/download/{filename}")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "下载文件接口")
    public void down(@PathVariable String filename,HttpServletResponse response) throws IOException {
        FileDownloadUtil.downLoadfile(uploadPath + filename,filename,response);
    }


    public static String getFileExtension(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (originalFilename != null && !originalFilename.isEmpty()) {
            int dotIndex = originalFilename.lastIndexOf('.');
            if (dotIndex > 0 && dotIndex < originalFilename.length() - 1) {
                return originalFilename.substring(dotIndex + 1);
            }
        }
        return null;
    }
}
